package cn.tworice.client.service;

import cn.tworice.client.dao.GoodsImgDao;
import cn.tworice.common.util.excel.InductsListenerService;
import cn.tworice.api.CrudService;
import cn.tworice.client.dao.GoodsDao;
import cn.tworice.common.entity.code.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService implements InductsListenerService<Goods>, CrudService<Goods> {
    @Autowired
    private GoodsDao dao;

    @Autowired
    private GoodsImgDao goodsImgDao;

    @Override
    public List<Goods> list(Integer page, Integer pageSize, Goods entity) {
        List<Goods> goods = dao.queryList(page * pageSize, pageSize, entity);
        for (Goods item : goods) {
            GoodsImg goodsImg = new GoodsImg();
            goodsImg.setGoodsId(item.getId());
            item.setImg(goodsImgDao.queryList(0, 20, goodsImg));
        }
        return goods;
    }

    @Override
    public int total(Goods entity) {
        return dao.queryTotal(entity);
    }

    @Override
    public int set(Goods entity) {
        entity.setUpdateTime(System.currentTimeMillis());
        if (entity.getId() == null) {
            entity.setCreateTime(System.currentTimeMillis());
            return dao.insert(entity);
        } else {
            return dao.update(entity);
        }
    }

    @Override
    public boolean update(Goods entity) {
        return dao.update(entity) == 1;
    }

    @Override
    public int del(Integer[] ids) {
        return dao.del(ids);
    }

    @Override
    public int save(List<Goods> list) {
        list.forEach(item -> {
            item.setCreateTime(System.currentTimeMillis());
            item.setUpdateTime(System.currentTimeMillis());
        });
        return dao.insertList(list);
    }

    @Override
    public Goods info(int id) {
        GoodsImg goodsImg = new GoodsImg();
        goodsImg.setGoodsId(id);
        Goods goods = dao.queryInfo(id);
        goods.setImg(goodsImgDao.queryList(0, 20, goodsImg));
        return goods;
    }
}